from flask import Blueprint, render_template, request, abort
from webapp.plugins import cache_utils as cache
from webapp.plugins.functions import CheckInfo
from webapp import redis_store
from webapp.const import RedisKey
from webapp.models import Pic, Work, Setting
from flask_login import login_required, current_user
import math


work_blueprint = Blueprint(
    'work',
    __name__
)


@work_blueprint.route('/', methods=['POST', 'GET'])
@login_required
def home():
    """显示temp文件或文件夹数量"""
    works = Work.query.order_by(Work.priority.desc(), Work.update_time.desc(), Work.create_time.desc()).all()
    settings = Setting.query.all()
    return render_template('work.html',
                           title='Work',
                           checkinfo=CheckInfo(),
                           works=works,
                           settings=settings,
                           user=current_user,
                           )


# 展示数据库记录不存在的文件
@work_blueprint.route('/db_lost', methods=['POST', 'GET'])
@login_required
def db_lost_pic():
    pass
    # db_error_list = redis_store.get('check_task_dbr_lost_list')
    # db_error_list = eval(db_error_list) if db_error_list else ''
    # count = redis_store.get('check_task_dbr_lost_count')
    #
    # pics = []
    # for file_name in db_error_list:
    #     pic_dict = {
    #         'file_name': file_name,
    #         'url': '/'.join(['piclab/pic', file_name[0], file_name]),
    #         'thumbnail_url': '/'.join(['sm', file_name[0], file_name])
    #     }
    #     pics.append(pic_dict)
    #
    # return render_template('db_lost.html',
    #                        title='db记录丢失的图片({})'.format(count),
    #                        count=count,
    #                        pics=pics,
    #                        album={'label': 'work', 'id': 0, 'fake': True},
    #                        )


# 展示文件不存在的数据库记录
@work_blueprint.route('/file_lost', methods=['POST', 'GET'])
@login_required
def file_lost_pic():
    pass
    # file_lost_list = redis_store.get('check_task_file_lost_db_list')
    # file_lost_list = eval(file_lost_list) if file_lost_list else ''
    # file_lost_list = list(map(lambda x: x[:-4], file_lost_list))
    #
    # pics = Pic.query.filter(Pic.file_name.in_(file_lost_list)).all()
    #
    # count = redis_store.get('check_task_file_lost_db_count')
    # return render_template('file_lost.html',
    #                        title='文件丢失的db记录({})'.format(count),
    #                        count=count,
    #                        pics=pics,
    #                        album={'label': 'work', 'id': 0, 'fake': True},
    #                        )


# 展示缺少缩略图的图片
@work_blueprint.route('/thumbnail_lost', methods=['POST', 'GET'])
@login_required
def thumbnail_lost_pic():
    pass
    # thumbnail_lost_list = redis_store.get('check_task_thumbnail_lost_list')
    # thumbnail_filename_list = eval(thumbnail_lost_list) if thumbnail_lost_list else ''
    # thumbnail_lost_list = map(lambda x: x[:-4], thumbnail_filename_list)
    #
    # pics = Pic.query.filter(Pic.file_name.in_(thumbnail_lost_list)).all()
    #
    # no_db_pic = []
    # for pic in thumbnail_filename_list:
    #
    #     if not Pic.query.filter_by(file_name=pic[:-4]).count():
    #         pic_dict = {
    #             'file_name': pic,
    #             'url': '/'.join(['piclab/pic', pic[0], pic])
    #         }
    #         no_db_pic.append(pic_dict)
    #
    # count = redis_store.get('check_task_thumbnail_lost_count')
    # return render_template('simple_album.html',
    #                        title='缩略图丢失的图片({})'.format(count),
    #                        count=count,
    #                        pics=pics,
    #                        no_db_pic=no_db_pic,
    #                        album={'label': 'work', 'id': 0, 'fake': True},
    #                        )


# 展示图片文件不存在的缩略图
@work_blueprint.route('/file_lost_thumbnail', methods=['POST', 'GET'])
@login_required
def file_lost_thumbnail():
    pass
    # file_lost_list = redis_store.get('check_task_file_lost_thumbnail_list')
    # file_lost_list = eval(file_lost_list) if file_lost_list else ''
    # count = redis_store.get('check_task_dbr_lost_count')
    #
    # pics = []
    # for file_name in file_lost_list:
    #     pic_dict = {
    #         'file_name': file_name,
    #         'url': '/'.join(['piclab/sm', file_name[0:2], file_name])
    #     }
    #     pics.append(pic_dict)
    # return render_template('db_lost.html',
    #                        title='图片丢失的缩略图({})'.format(count),
    #                        count=count,
    #                        pics=pics,
    #                        album={'label': 'work', 'id': 0, 'fake': True},
    #                        )


@work_blueprint.route('/logs/<log_type>')
@login_required
def logs(log_type):
    per_page_logs = Setting.get('per_page_logs')
    try:
        page = request.args.get('page', 1, type=int)
    except ValueError:
        page = 1
    items_count = redis_store.llen(log_type)
    page_count = math.ceil(items_count / per_page_logs)
    logs_raw = redis_store.lrange(log_type, per_page_logs * (page-1), per_page_logs * page-1)
    if not logs_raw:
        abort(404)
    return render_template('logs.html',
                           title='{}'.format(log_type),
                           logs_raw=logs_raw,
                           page_now=page,
                           page_count=page_count,
                           per_page_logs=per_page_logs,
                           )


@work_blueprint.route('/page/<int:page_id>')
@login_required
def work_page(page_id):
    page = Work.query.get_or_404(page_id)

    return render_template('work_page.html',
                           page=page,
                           title=page.title,
                           )


@work_blueprint.route('/page_edit/<int:page_id>')
@login_required
def work_page_edit(page_id):
    page = Work.query.get_or_404(page_id)

    return render_template('work_page_edit.html',
                           page=page,
                           title=page.title,
                           )


@work_blueprint.route('/temp')
@login_required
def temp_pics():
    try:
        page = request.args.get('page', 0, type=int)
    except ValueError:
        page = 0

    return render_template('temp_pic.html',
                           page=page,
                           source='temp',
                           source_id='',
                           album={'label': 'temp', 'id': 0, 'fake': True, 'amount': cache.hlen(RedisKey.temp_pics_hash)},
                           )


@work_blueprint.route('/recycle')
@login_required
def recycle():
    try:
        page = request.args.get('page', 0, type=int)
    except ValueError:
        page = 0
    return render_template('album.html',
                           page=page,
                           source_id='',
                           album={'label': 'recycle', 'id': 0, 'fake': True, 'meta': {}, 'amount': Pic.query.filter(Pic.delete_time.isnot(None)).count()},
                           )
